import yaml
import json
import os


def parse_file(path):
    obj = None
    with open(path, "r", encoding="utf-8") as f:
        if path.endswith('.yml') or path.endswith('.yaml'):
            obj = yaml.load(f, Loader=yaml.UnsafeLoader)
        elif path.endswith('.json'):
            obj = json.loads(f.read())
        elif '.' not in os.path.basename(path):
            obj = dict([(i.strip(), None) for i in f.readlines() if i.strip()])
    return obj


def scan_docs(path):
    docs = {}
    for filename in os.listdir(path):
        child = os.path.join(path, filename)
        name = filename.split('.')[0]
        if os.path.isdir(child):
            print("dir: {}".format(child))
            content_dir = scan_docs(child)
            docs.setdefault(name, {}).update(content_dir)
        else:
            content_file = parse_file(child)
            if name == 'global':
                docs.update(content_file)
            else:
                docs.setdefault(name, {}).update(content_file)
    return docs


if __name__ == '__main__':
    import sys

    if len(sys.argv) != 2:
        print('Usage: %s <cluster-name>' % sys.argv[0])
        sys.exit(1)
    cluster = sys.argv[1]
    inventory_dir = os.path.dirname(os.path.abspath(__file__))
    docs = scan_docs(os.path.join(inventory_dir, cluster))
    output = {}

    for attr_name, attr in docs.items():
        if isinstance(attr, dict):
            for group_name, group in attr.items():
                if isinstance(group, dict):
                    output.setdefault(group_name, {}).setdefault(attr_name, {}).update(group)

    with open(os.path.join(inventory_dir, cluster + '.yaml'), 'w', encoding="utf-8") as f:
        yaml.dump(output, f, default_flow_style=False, encoding="utf-8", allow_unicode=True)
